//
//  StatusListViewModel.swift
//  Weibo
//
//  Created by 张远文 on 16/4/30.
//  Copyright © 2016年 张远文. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class StatusListViewModel: NSObject {

    class func loadData(since_id since_id: Int, max_id: Int, finished:(array: [Status]?) -> ()) {
        
        let urlString = "2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().token else {
            
            SVProgressHUD.showWithStatus("您没有登录")
            return
        }
        
        //编辑请求参数
        var parameters = ["access_token" : token]
        
        //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
        if since_id > 0 {
            
            parameters["since_id"] = "\(since_id)"
        }
        
        //若指定此参数，则返回ID小于或等于max_id的微博，默认为0
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parameters) { (result, error) in
            if error != nil {
                
                finished(array: nil)
                return
            }
            
            if let array = result!["statuses"] as? [[String : AnyObject]] {
                
                var list = [Status]()
                
                for item in array {
                    //字典转模型
                    let s = Status(dict: item)
                    //添加微博对象
                    list.append(s)
                }
                
                //完成单张图片缓存
                StatusListViewModel.cacheStatusImage(list, finished: finished)
            }
        }
        
    }
    
    private class func cacheStatusImage(array: [Status], finished:(array:[Status]?) -> ()) {
        
        //缓存单张照片
        if array.count == 0 {
            finished(array: nil)
            return
        }
        
        //创建任务队列群组
        let group = dispatch_group_create()
        
        //遍历模型数组
        for s in array {
            if let imageurls = s.pictureURLs {
                
                if imageurls.count != 1 {
                    continue
                }
                
                //一定是单张图片
                for url in imageurls {
                    //开始下载图片
                    //异步加载图片的开始
                    //向群组中添加异步任务
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                        
                        print("单张图片下载完成")
                        //异步任务离开群组
                        dispatch_group_leave(group)
                    })
                }
                
                dispatch_group_notify(group, dispatch_get_main_queue(), { 
                    
                    //在主线程完成回调
                    print("所有的异步图片下载完成")
                    finished(array: array)
                })
            }
        }
        
        
    }
    
    
    
}
